package com.zslibrary.Protocol;

import android.content.Context;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.zslibrary.BusMaster.MyLanguage;
import com.zslibrary.Enum.PropertyDefine;
import com.zslibrary.Structure.ComponentGateStruct;
import com.zslibrary.Structure.ComponentStruct;
import com.zslibrary.Structure.ConfigurableComponentStruct;
import com.zslibrary.Structure.CraftStrcut;
import com.zslibrary.Structure.DefaultAdjustmentStruct;
import com.zslibrary.Structure.GateStruct;
import com.zslibrary.Structure.IngredientStruct;
import com.zslibrary.Structure.ProdComponentStruct;
import com.zslibrary.Structure.ProdGateStruct;
import com.zslibrary.Structure.ProdIngredientStruct;
import com.zslibrary.Structure.RecipeGateStruct;
import com.zslibrary.Tools.ZSLog;

public class Machine {
    private static Boolean isInitialized = false;
    private static String machineModle;
    private static String machineName;
    private static String createDate;
    private static String modifyDate;
    private static SparseIntArray componentGateList = new SparseIntArray();
    private static List<GateStruct> requestGateList=new LinkedList<>();
    private static List<RecipeGateStruct> allRecipeGateList = new LinkedList<>();
    private static SparseArray<ComponentStruct> componentList = null;    /*component list*/
    private static SparseArray<CraftStrcut> craftList = null;   /*craft list*/
    private static SparseArray<IngredientStruct> ingrDescriptionList = null;  /*ingredient list*/
    private static List<DefaultAdjustmentStruct> defaultAdjustmentList = null; /*default adjustment list*/
    private static SparseArray<ConfigurableComponentStruct[]> configurableComponents =new SparseArray<>();
    public final int OPTION_NONE = 0;
    public final int OPTION_CPNCENTRATIONS = 1;
    public final int OPTION_EXIST = 2;

    public static Boolean readMachine(Context context, String configPath) {
        if (!isInitialized) {
            isInitialized = true;
            BufferedReader reader = null;
            StringBuilder content = new StringBuilder();
            JSONArray componentsJson;
            JSONArray recipesJson;
            JSONArray ingredientsJson;
            defaultAdjustmentList = new LinkedList<>();
            componentList = new SparseArray<ComponentStruct>();
            try {
                String fileName = getFileName(configPath);
                reader = new BufferedReader(new FileReader(configPath + "/"+fileName));
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }


                ingrDescriptionList = new SparseArray<IngredientStruct>();
//                recipeList = new SparseArray<RecipeStruct>();
                craftList = new SparseArray<>();
                JSONObject allJson = new JSONObject(content.toString());
                componentsJson = allJson.getJSONArray("componentList");
                machineName = allJson.getString("name");
                machineModle = allJson.getString("model");
                createDate = allJson.getString("createDate");
                modifyDate = allJson.getString("modifyDate");
                for (int i = 0; i < componentsJson.length(); i++) {
                    ComponentStruct comp = new ComponentStruct();
                    JSONObject componentJson = componentsJson.getJSONObject(i);
                    comp.id = componentJson.getInt("id");
                    comp.name = (MyLanguage.getLanguage()==0?componentJson.getString("name"):componentJson.getString("name_en"));
                    comp.available = componentJson.getBoolean("available");
                    comp.configurable = componentJson.getBoolean("configurable");
                    comp.property = componentJson.getInt("property");

                    if(componentJson.isNull("gates"))
                        comp.gates=null;
                    else{
                        JSONArray gatesJson = componentJson.getJSONArray("gates");
                        comp.gates = new ComponentGateStruct[gatesJson.length()];
                        for (int j = 0; j < gatesJson.length(); j++) {
                            JSONObject gateJson = gatesJson.getJSONObject(j);
                            ComponentGateStruct gate = new ComponentGateStruct();
                            gate.id = gateJson.getInt("id");
                            gate.type = gateJson.getInt("type");
                            comp.gates[j] = gate;
                            componentGateList.put(comp.id, gate.id);
                        }
                    }
                    componentList.put(comp.id, comp);
                }
                recipesJson = allJson.getJSONArray("recipeList");
                for (int i = 0; i < recipesJson.length(); i++) {
                    CraftStrcut craft = new CraftStrcut();
                    JSONObject recipeJson = recipesJson.getJSONObject(i);
                    craft.id = recipeJson.getInt("id");
                    craft.name = recipeJson.getString("name");
                    JSONArray pComponentsJson = recipeJson.getJSONArray("prodComponents");
                    craft.prodComponent = new ProdComponentStruct[pComponentsJson.length()];
                    for (int j = 0; j < pComponentsJson.length(); j++) {
                        ProdComponentStruct component = new ProdComponentStruct();
                        JSONObject pComponentJson = pComponentsJson.getJSONObject(j);
//                        JSONObject defaultAdjJson = pComponentJson.getJSONObject("defaultAdj");
                        JSONObject ingredientJson = null;
                        JSONObject parentJson = null;
                        JSONObject meJson = null;
                        JSONArray adjsJson = null;

                        ProdGateStruct me = new ProdGateStruct();
                        RecipeGateStruct recipeGate = null;
                        meJson = pComponentJson.getJSONObject("me");
                        me.componentId = meJson.getInt("componentId");
                        me.gateId = meJson.getInt("gateId");
                        me.fluid = meJson.getInt("fluid");
                        component.me = me;
                        recipeGate = new RecipeGateStruct();
                        recipeGate.recipeId = craft.id;
                        recipeGate.componentId = me.componentId;
                        recipeGate.gateId = me.gateId;
                        allRecipeGateList.add(recipeGate);    /*用来判断产品的gate status*/
                        if (!meJson.isNull("defaultAdjs")) {
                            adjsJson = meJson.getJSONArray("defaultAdjs");
                            for (int k = 0; k < adjsJson.length(); k++) {
                                JSONObject adjJson = adjsJson.getJSONObject(k);
                                DefaultAdjustmentStruct adjustment = new DefaultAdjustmentStruct();
                                adjustment.adjustmentId = (byte) adjJson.getInt("adjId");
                                adjustment.componentId = (short) me.componentId;
                                adjustment.fluid = (byte) me.fluid;
                                adjustment.scheme = (byte) adjJson.getInt("scheme");
                                adjustment.productId = (short) craft.id;
                                adjustment.value = (short) adjJson.getInt("value");
                                defaultAdjustmentList.add(adjustment);
                            }
                        }
                        if (!pComponentJson.isNull("ingredient")) {
                            ingredientJson = pComponentJson.getJSONObject("ingredient");
                            ProdIngredientStruct ingr = new ProdIngredientStruct();
                            ingr.descriptionId = ingredientJson.getInt("descriptionId");
                            ingr.max = ingredientJson.getInt("max");
                            ingr.min = ingredientJson.getInt("min");
                            ingr.std = ingredientJson.getInt("std");
                            ingr.option = ingredientJson.getInt("option");
                            component.ingredient = ingr;
                        } else
                            component.ingredient = null;
                        if (!pComponentJson.isNull("parent")) {
                            parentJson = pComponentJson.getJSONObject("parent");
                            ProdGateStruct parent = new ProdGateStruct();
                            parent.componentId = parentJson.getInt("componentId");
                            parent.gateId = parentJson.getInt("gateId");
                            parent.fluid = parentJson.getInt("fluid");
                            component.parent = parent;
                            recipeGate = new RecipeGateStruct();
                            recipeGate.recipeId = craft.id;
                            recipeGate.componentId = parent.componentId;
                            recipeGate.gateId = parent.gateId;
                            allRecipeGateList.add(recipeGate);    /*用来判断产品的gate status*/

                            if (!parentJson.isNull("defaultAdjs")) {
                                adjsJson = parentJson.getJSONArray("defaultAdjs");
                                for (int k = 0; k < adjsJson.length(); k++) {
                                    JSONObject adjJson = adjsJson.getJSONObject(k);
                                    DefaultAdjustmentStruct adjustment = new DefaultAdjustmentStruct();
                                    adjustment.adjustmentId = (byte) adjJson.getInt("adjId");
                                    adjustment.componentId = (short) parent.componentId;
                                    adjustment.fluid = (byte) parent.fluid;
                                    adjustment.scheme = (byte) adjJson.getInt("scheme");
                                    adjustment.productId = (short) craft.id;
                                    adjustment.value = (short) adjJson.getInt("value");
                                    defaultAdjustmentList.add(adjustment);
                                }
                            }
                        } else
                            component.parent = null;
                        craft.prodComponent[j] = component;
                    }
//                    recipeList.put(recipe.id, recipe);
                    craftList.put(craft.id, craft);
                }
                ingredientsJson = allJson.getJSONArray("ingredientDescription");
                for (int i = 0; i < ingredientsJson.length(); i++) {
                    IngredientStruct ingredient = new IngredientStruct();
                    JSONObject ingredientJson = ingredientsJson.getJSONObject(i);

                    ingredient.id = ingredientJson.getInt("id");
                    ingredient.name = ingredientJson.getString("name");
                    ingredient.unit = ingredientJson.getString("unit");
                    ingredient.unitType = ingredientJson.getInt("unitType");
                    ingredient.property = ingredientJson.getInt("property");
                    ingrDescriptionList.put(ingredient.id, ingredient);
                }
                for(int i=0;i<craftList.size();i++){
                    List<ConfigurableComponentStruct>tempComp=new ArrayList<>();
                    /*TODO:需要修改*/
                    Boolean hasSolvent=false;
                    for(ProdComponentStruct component:craftList.valueAt(i).prodComponent){
                        ComponentStruct componentInfo=getComponentInfo(component.parent.componentId);
                        if(componentInfo.configurable){
                            if(componentInfo.property== PropertyDefine.SOLVENT_INGR) {
                                if(!hasSolvent)
                                    hasSolvent = true;
                                else
                                    continue;
                            }
                            ConfigurableComponentStruct comp=new ConfigurableComponentStruct();
                            comp.id = componentInfo.id;
                            comp.avalaible=componentInfo.available;
                            comp.name=componentInfo.name;
                            comp.property=componentInfo.property;
                            tempComp.add(comp);
                        }
                    }
                    ConfigurableComponentStruct[] toArray=new ConfigurableComponentStruct[tempComp.size()];
                    configurableComponents.put(craftList.valueAt(i).id,tempComp.toArray(toArray));
                }
                for(RecipeGateStruct recipeGate:allRecipeGateList){
                    GateStruct gate=new GateStruct();
                    Boolean breakOne=false;
                    gate.componentId=(short)recipeGate.componentId;
                    gate.gateId=(byte)recipeGate.gateId;
                    for(GateStruct requestGate:requestGateList){
                        if(requestGate.componentId==recipeGate.componentId && requestGate.gateId==recipeGate.gateId){
                            breakOne=true;
                            break;
                        }
                    }
                    if(!breakOne)
                        requestGateList.add(gate);
                }
            } catch (Exception e) {
                /*TODO:读取机型文件报错*/
                ZSLog.d( e.toString());
            } finally {
                try {
                    reader.close();
                } catch (Exception e) {

                }
            }
        }
        return true;
    }

    public static SparseIntArray getComponentGateList() {
        return componentGateList;
    }

    public static List<GateStruct> getRequestGateList(){
        return requestGateList;
    }

    public static List<RecipeGateStruct> getAllRecipeGateList() {
        return allRecipeGateList;
    }

    public static List<DefaultAdjustmentStruct> getDefaultAdjustments() {
        return defaultAdjustmentList;
    }

    public static SparseArray<CraftStrcut> getCrafts() {
        return craftList;
    }

    public static SparseArray<IngredientStruct> getIngrDescription() {
        return ingrDescriptionList;
    }

    public static SparseArray<ComponentStruct> getComponentList() {
        return componentList;
    }

    public static ComponentStruct getComponentInfo(int componentId) {
        return componentList.get(componentId);
    }

    public static ConfigurableComponentStruct[] getConfigurableComponents(int craftId){
        return configurableComponents.get(craftId);
    }

    public static String getFileName(String filePath){
        String fileName = "";
        File FilePath = new File(filePath);
        File[] files = FilePath.listFiles();
        for (File fileTemp : files) {
            if (fileTemp.isDirectory()) {
//                System.out.println(temp + "目录 :" + fileTemp.getName()
//                        + "\t");
//                queryFile(fileTemp, temp + "\t");
            } else {
                if(fileTemp.getName().contains("zsRcp"))
                    fileName = fileTemp.getName();
            }
        }
        return fileName;
    }
}
